public class Sort {

    public static void sort(int[] nums) {
        sort(nums, 0, nums.length - 1);
    }

    public static void sort(int[] nums, int lo, int hi) {
        if (lo >= hi) {
            return;
        }
        int mid = lo + (hi - lo) / 2;
        sort(nums, lo, mid);
        sort(nums, mid + 1, hi);
        merge(nums, lo, mid, hi);
    }

    public static void merge(int[] nums, int lo, int mid, int hi) {
        int[] temp = new int[hi - lo + 1];
        for (int i = lo; i <= hi; i++) {
            temp[i - lo] = nums[i];
        }
        int index = lo;
        int i = 0, j = mid + 1 - lo;
        while (i <= mid - lo || j <= hi - lo) {
            if (i > mid - lo) {
                nums[index++] = temp[j++];
            } else if (j > hi - lo) {
                nums[index++] = temp[i++];
            } else if (temp[i] <= temp[j]) {
                nums[index++] = temp[i++];
            } else {
                nums[index++] = temp[j++];
            }
        }
     }

    public static void main(String[] args) {
        int[] nums = {4, 3, 0, 8, 1, 7};
        sort(nums);
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
    }

}
